package rm.ep.server;

import java.util.List;

import rm.ep.shared.BlobEntity;
import rm.ep.shared.FileEntity;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.Query;

public class FileDAO extends BaseDAO {

	public FileEntity insert(String fileName, String fileType, final byte[] file) {
		final FileEntity f = new FileEntity(fileName, fileType, file.length);
		transact(new Transactable() {
			@Override
			public void execute(Objectify ofy) {
				Key<FileEntity> fKey = ofy.put(f);
				ofy.put(new BlobEntity(file, fKey));
			}
		});
		return f;
	}
	
	public FileEntity select(Long id) {
		return ofy().get(FileEntity.class, id);
	}

	public BlobEntity selectBlob(Long fileId) {
		FileEntity f = select(fileId);
		List<BlobEntity> l = ofy().query(BlobEntity.class).ancestor(f).list();
		if (l.size() != 1) {
			throw new IllegalStateException("Every FileEntity MUST have ONE Blob: " + l.size());
		}
		return l.get(0);
	}
	
	public int purgeInActive() {
		long yesterday = System.currentTimeMillis() - 1000*60*60*24;
		Query<FileEntity> q = ofy().query(FileEntity.class)
									.filter("fIsActive", false)
									.filter("fModifiedAt < ", yesterday);
		for (FileEntity f : q) {
			ofy().delete(ofy().query(BlobEntity.class).ancestor(f).fetchKeys());
		}
		ofy().delete(q);
		return q.count();
	}

}
